import socket
from datetime import date

# udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# udp.bind(('0.0.0.0', 514))
def syslog_monitor(path):
    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp.bind(('0.0.0.0', 514))
    while True:
        rec_msg, addr = udp.recvfrom(2048)
        client_ip, client_port = addr
        msg = rec_msg.rstrip(b'\x00').decode('utf-8', 'ignore')
        log = "日志来源IP：" + client_ip + " 日志ID：" + msg[5:]
        print(log)
        filename = path + client_ip + '_' + str(date.today()) + ".log"
        with open(filename, 'a+', encoding="utf-8") as f:
            f.write(log + "\n")

if __name__ == "__main__":
    print("欢迎使用SYSLOG服务器\n")
    print("请选择需要保存日志的文件夹\n")
    path = "C:/Users/lovey/Desktop/1/"
    syslog_monitor(path)
